<template>
  <div class="quotation-edit" v-loading="loading">
    <el-form :model="quotationForm" :rules="rules" ref="quotationFormRef" label-width="120px">
      <!-- 基本信息 -->
      <el-card class="form-section">
        <template #header>
          <span>报价基本信息</span>
        </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="报价单号">
              <el-input v-model="quotationForm.quotationNo" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户代码" prop="customerCode">
              <el-select v-model="quotationForm.customerCode" filterable
                         placeholder="请选择客户代码" @change="handleCustomerChange">
                <el-option v-for="customer in customers" :key="customer.customerCode" 
                          :label="customer.customerCode" :value="customer.customerCode"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerName">
              <el-select v-model="quotationForm.customerName" filterable
                         placeholder="请选择客户名称" @change="handleCustomerNameChange">
                <el-option v-for="customer in customers" :key="customer.customerCode" 
                          :label="customer.customerName" :value="customer.customerName"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="业务员" prop="salesperson">
              <el-select v-model="quotationForm.salesperson" filterable
                         placeholder="请选择业务员">
                <el-option v-for="emp in employees" :key="emp.employeeCode" 
                          :label="emp.employeeName" :value="emp.employeeName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编号">
              <el-input v-model="quotationForm.contractNo" placeholder="可选"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单日期" prop="orderDate">
              <el-date-picker v-model="quotationForm.orderDate" type="date" 
                             value-format="YYYY-MM-DD" placeholder="选择订单日期"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="是否含税">
              <el-select v-model="quotationForm.isTaxIncluded" placeholder="选择是否含税">
                <el-option label="否" :value="false"/>
                <el-option label="增值税票 13%" :value="true"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-select v-model="quotationForm.paymentMethod" filterable allow-create default-first-option
                         placeholder="选择或输入付款方式">
                <el-option label="现金" value="现金"/>
                <el-option label="月结30天" value="月结30天"/>
                <el-option label="月结60天" value="月结60天"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-tag :type="getStatusTagType(quotationForm.status)" size="large">
                {{ quotationForm.status }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="quotationForm.remark" type="textarea" :rows="2" placeholder="备注信息"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 物料信息 -->
      <el-card class="form-section">
        <template #header>
          <span>物料信息</span>
          <el-button type="primary" size="small" @click="addItem" style="float: right;">
            添加物料
          </el-button>
        </template>

        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="基本信息" name="basic">
            <el-table :data="quotationForm.items" border max-height="600">
              <el-table-column prop="itemNo" label="序号" width="60" fixed="left"/>
              <el-table-column label="产品名称" width="150" fixed="left">
                <template #default="{row}">
                  <el-input v-model="row.productName" size="small" placeholder="输入产品名称"/>
                </template>
              </el-table-column>
              <el-table-column label="物料编码" width="120">
                <template #default="{row}">
                  <el-input v-model="row.materialCode" size="small" placeholder="物料编码"/>
                </template>
              </el-table-column>
              <el-table-column label="层数" width="100">
                <template #default="{row}">
                  <el-select v-model="row.layers" filterable allow-create default-first-option size="small" placeholder="层数">
                    <el-option label="1" value="1"/>
                    <el-option label="2" value="2"/>
                    <el-option label="4" value="4"/>
                    <el-option label="6" value="6"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="板厚(mm)" width="120">
                <template #default="{row}">
                  <el-select v-model="row.thickness" filterable allow-create default-first-option size="small" placeholder="板厚">
                    <el-option label="0.6" value="0.6"/>
                    <el-option label="0.8" value="0.8"/>
                    <el-option label="1.0" value="1.0"/>
                    <el-option label="1.2" value="1.2"/>
                    <el-option label="1.6" value="1.6"/>
                    <el-option label="2.0" value="2.0"/>
                    <el-option label="2.5" value="2.5"/>
                    <el-option label="3.0" value="3.0"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="表面处理" width="120">
                <template #default="{row}">
                  <el-select v-model="row.surfaceTreatment" filterable allow-create default-first-option size="small" placeholder="表面处理">
                    <el-option label="有铅喷锡" value="有铅喷锡"/>
                    <el-option label="无铅喷锡" value="无铅喷锡"/>
                    <el-option label="OSP" value="OSP"/>
                    <el-option label="沉金" value="沉金"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="阻焊" width="100">
                <template #default="{row}">
                  <el-select v-model="row.solderMask" filterable allow-create default-first-option size="small" placeholder="阻焊颜色">
                    <el-option label="绿油" value="绿油"/>
                    <el-option label="红油" value="红油"/>
                    <el-option label="白油" value="白油"/>
                    <el-option label="黑油" value="黑油"/>
                    <el-option label="蓝油" value="蓝油"/>
                    <el-option label="黄油" value="黄油"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="字符" width="100">
                <template #default="{row}">
                  <el-select v-model="row.character" filterable allow-create default-first-option size="small" placeholder="字符颜色">
                    <el-option label="白字" value="白字"/>
                    <el-option label="黑字" value="黑字"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="板材" width="100">
                <template #default="{row}">
                  <el-input v-model="row.boardMaterial" size="small" placeholder="例如 FR-4"/>
                </template>
              </el-table-column>
              <el-table-column label="交货尺寸(mm)" width="120">
                <template #default="{row}">
                  <el-input v-model="row.deliverySize" size="small" placeholder="例如 100x100"/>
                </template>
              </el-table-column>
              <el-table-column label="拼版" width="100">
                <template #default="{row}">
                  <el-input v-model="row.panelization" size="small" placeholder="例如 1x1" @input="() => calculateAmount(row)"/>
                </template>
              </el-table-column>
              <el-table-column label="内铜" width="100">
                <template #default="{row}">
                  <el-select v-model="row.innerCopper" filterable allow-create default-first-option size="small" placeholder="内铜厚度">
                    <el-option label="0.5oz" value="0.5oz"/>
                    <el-option label="1oz" value="1oz"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="外铜" width="100">
                <template #default="{row}">
                  <el-select v-model="row.outerCopper" filterable allow-create default-first-option size="small" placeholder="外铜厚度">
                    <el-option label="0.5oz" value="0.5oz"/>
                    <el-option label="1oz" value="1oz"/>
                    <el-option label="1.5oz" value="1.5oz"/>
                    <el-option label="2oz" value="2oz"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="过孔工艺" width="120">
                <template #default="{row}">
                  <el-select v-model="row.viaProcess" filterable allow-create default-first-option size="small" placeholder="选择过孔工艺">
                    <el-option label="过孔盖油" value="过孔盖油"/>
                    <el-option label="过孔塞油" value="过孔塞油"/>
                    <el-option label="过孔开窗" value="过孔开窗"/>
                    <el-option label="树脂塞油" value="树脂塞油"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="测试" width="120">
                <template #default="{row}">
                  <el-select v-model="row.testing" filterable allow-create default-first-option size="small" placeholder="选择测试方式">
                    <el-option label="飞针测试" value="飞针测试"/>
                    <el-option label="测试架" value="测试架"/>
                    <el-option label="无" value="无"/>
                    <el-option label="自定义" value="自定义"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="数量" width="120">
                <template #default="{row}">
                  <el-input v-model="row.quantity" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row, 'quantity')"/>
                </template>
              </el-table-column>
              <el-table-column label="单价" width="120">
                <template #default="{row}">
                  <el-input v-model="row.unitPrice" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row, 'unitPrice', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="合计金额" width="120">
                <template #default="{row}">
                  <span>{{ (row.totalAmount || 0).toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="出货日期" width="120">
                <template #default="{row}">
                  <el-date-picker v-model="row.deliveryDate" type="date" size="small"
                                 value-format="YYYY-MM-DD" placeholder="出货日期"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="{row, $index}">
                  <el-button size="small" type="danger" @click="removeItem($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="价格计算" name="calculation">
            <el-table :data="quotationForm.items" border max-height="600">
              <el-table-column prop="itemNo" label="序号" width="60"/>
              <el-table-column label="产品名称" width="150" prop="productName"/>
              <el-table-column label="宽(mm)" width="120">
                <template #default="{row}">
                  <el-input v-model="row.calculation.widthMm" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.calculation, 'widthMm', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="长(mm)" width="120">
                <template #default="{row}">
                  <el-input v-model="row.calculation.lengthMm" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.calculation, 'lengthMm', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="数量" width="120">
                <template #default="{row}">
                  <el-input v-model="row.calculation.quantity" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.calculation, 'quantity')"/>
                </template>
              </el-table-column>
              <el-table-column label="订单面积(mm²)" width="120">
                <template #default="{row}">
                  <span>{{ (row.calculation.orderAreaMm || 0).toFixed(4) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="平米价(元)" width="120">
                <template #default="{row}">
                  <el-input v-model="row.calculation.pricePerSqm" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.calculation, 'pricePerSqm', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="未税单价(元)" width="120">
                <template #default="{row}">
                  <span>{{ (row.calculation.untaxUnitPrice || 0).toFixed(4) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="未税金额" width="100">
                <template #default="{row}">
                  <span>{{ (row.calculation.untaxAmount || 0).toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="含税总金额" width="120">
                <template #default="{row}">
                  <span>{{ (row.calculation.taxTotalAmount || 0).toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="备注" width="200">
                <template #default="{row}">
                  <el-input v-model="row.itemRemark" size="small" type="textarea" 
                           :rows="1" placeholder="请输入备注"/>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="成本明细" name="costs">
            <el-table :data="quotationForm.items" border max-height="600">
              <el-table-column prop="itemNo" label="序号" width="60"/>
              <el-table-column label="产品名称" width="150" prop="productName"/>
              <el-table-column label="起步价" width="120">
                <template #default="{row}">
                  <el-input v-model="row.costs.basePrice" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.costs, 'basePrice', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="阻燃费" width="120">
                <template #default="{row}">
                  <el-input v-model="row.costs.flameRetardantFee" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.costs, 'flameRetardantFee', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="沉铜费" width="120">
                <template #default="{row}">
                  <el-input v-model="row.costs.copperPlatingFee" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.costs, 'copperPlatingFee', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="表面处理费" width="120">
                <template #default="{row}">
                  <el-input v-model="row.costs.surfaceTreatmentFee" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.costs, 'surfaceTreatmentFee', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="工程费" width="120">
                <template #default="{row}">
                  <el-input v-model="row.costs.engineeringFee" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.costs, 'engineeringFee', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="运费" width="120">
                <template #default="{row}">
                  <el-input v-model="row.costs.shippingFee" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.costs, 'shippingFee', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="铜厚费" width="120">
                <template #default="{row}">
                  <el-input v-model="row.costs.copperThicknessFee" size="small" type="text" class="number-input"
                           @input="value => onInputChange(value, row.costs, 'copperThicknessFee', true)"/>
                </template>
              </el-table-column>
              <el-table-column label="合计" width="100">
                <template #default="{row}">
                  <span>{{ getCostTotal(row.costs).toFixed(2) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      
      <!-- 汇总信息 -->
      <el-card class="form-section">
        <template #header>
          <span>汇总信息</span>
        </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="总金额">
              <el-input :value="(quotationForm.totalAmount || 0).toFixed(2)" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="含税总金额">
              <el-input :value="(quotationForm.totalTaxAmount || 0).toFixed(2)" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <!-- 底部操作按钮 -->
    <div class="footer-actions">
      <el-button @click="$emit('close', false)">取消</el-button>
      <el-button @click="saveDraft" :loading="saving">保存草稿</el-button>
      <el-button type="primary" @click="saveQuotation" :loading="submitting">保存</el-button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { quotationAPI, customerAPI, employeeAPI } from '../utils/api'

export default {
  name: 'QuotationEdit',
  props: {
    quotationId: {
      type: Number,
      required: true
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const quotationFormRef = ref(null)
    const activeTab = ref('basic')
    const loading = ref(false)
    const saving = ref(false)
    const submitting = ref(false)
    
    // 表单数据
    const quotationForm = reactive({
      id: null,
      quotationNo: '',
      customerCode: '',
      customerName: '',
      salesperson: '',
      contractNo: '',
      orderDate: '',
      isTaxIncluded: false,
      paymentMethod: '',
      totalAmount: 0,
      totalTaxAmount: 0,
      status: '草稿',
      remark: '',
      items: []
    })
    
    // 选项数据
    const customers = ref([])
    const employees = ref([])
    
    // 表单验证规则
    const rules = {
      customerCode: [{ required: true, message: '请选择客户代码', trigger: 'change' }],
      customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
      salesperson: [{ required: true, message: '请选择业务员', trigger: 'change' }],
      orderDate: [{ required: true, message: '请选择订单日期', trigger: 'change' }],
      paymentMethod: [{ required: true, message: '请选择付款方式', trigger: 'change' }]
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case '草稿': return 'info'
        case '已提交': return 'primary'
        case '已生成合同': return 'success'
        case '已审核': return 'success'
        case '已拒绝': return 'danger'
        default: return 'info'
      }
    }
    
    // 添加物料
    const addItem = () => {
      const itemNo = quotationForm.items.length + 1
      quotationForm.items.push({
        itemNo,
        productName: '',
        materialCode: '',
        layers: '4',
        thickness: '1.6',
        surfaceTreatment: '无铅喷锡',
        solderMask: '绿油',
        character: '白字',
        boardMaterial: 'FR-4',
        deliverySize: '',
        panelization: '',
        innerCopper: '1oz',
        outerCopper: '1oz',
        viaProcess: '',
        testing: '',
        testingFee: 0,
        isUrgent: false,
        quantity: 100,
        unitPrice: 0,
        sampleFee: 0,
        totalAmount: 0,
        deliveryDate: '',
        itemRemark: '',
        isTaxIncluded: false,
        paymentMethod: '',
        calculation: {
          widthMm: 0,
          lengthMm: 0,
          quantity: 100,
          orderAreaMm: 0,
          pricePerSqm: 0,
          untaxUnitPrice: 0,
          untaxAmount: 0,
          testingFee: 0,
          untaxTotalAmount: 0,
          taxTotalAmount: 0,
          taxUnitPrice: 0
        },
        costs: {
          basePrice: 0,
          flameRetardantFee: 0,
          copperPlatingFee: 0,
          surfaceTreatmentFee: 0,
          engineeringFee: 0,
          shippingFee: 0,
          copperThicknessFee: 0,
          oversizeHoleFee: 0,
          impedanceFee: 0,
          halfHoleFee: 0,
          mergePanelFee: 0,
          resinPlugHoleFee: 0,
          goldFingerFee: 0,
          totalCost: 0
        }
      })
    }
    
    // 删除物料
    const removeItem = (index) => {
      quotationForm.items.splice(index, 1)
      // 重新编号
      quotationForm.items.forEach((item, idx) => {
        item.itemNo = idx + 1
      })
      calculateTotalAmount()
    }
    
    // 解析拼版数量的辅助函数
    const parsePanelization = (panelizationStr) => {
      if (!panelizationStr || panelizationStr.trim() === '') {
        return 1; // 默认为1，避免除零错误
      }
      
      // 处理类似 "2x2", "1x3", "4x1" 等格式
      const match = panelizationStr.toString().match(/(\d+)[\s]*[x×*][\s]*(\d+)/i);
      if (match) {
        const width = parseInt(match[1]);
        const height = parseInt(match[2]);
        return width * height;
      }
      
      // 如果只是一个数字，直接返回
      const num = parseInt(panelizationStr);
      if (!isNaN(num) && num > 0) {
        return num;
      }
      
      // 默认返回1
      return 1;
    }
    
    // 计算单项金额
    const calculateAmount = (row) => {
      if (!row.calculation) return
      
      const panelCount = parsePanelization(row.panelization)
      
      // 计算订单面积 - 公式=长*宽/1000000/拼版*数量
      if (row.calculation.widthMm && row.calculation.lengthMm && row.calculation.quantity && panelCount > 0) {
        row.calculation.orderAreaMm = (row.calculation.widthMm * row.calculation.lengthMm / 1000000 / panelCount) * row.calculation.quantity
      }
      
      // 计算未税金额
      if (row.calculation.orderAreaMm && row.calculation.pricePerSqm) {
        row.calculation.untaxAmount = row.calculation.orderAreaMm * row.calculation.pricePerSqm
        row.calculation.untaxUnitPrice = row.calculation.untaxAmount / (row.calculation.quantity || 1)
      }
      
      // 计算含税总金额
      const taxRate = quotationForm.isTaxIncluded ? 1.13 : 1
      row.calculation.taxTotalAmount = (row.calculation.untaxAmount || 0) * taxRate
      row.calculation.taxUnitPrice = row.calculation.taxTotalAmount / (row.calculation.quantity || 1)
      
      // 更新物料项的总金额
      row.totalAmount = row.calculation.taxTotalAmount || (row.unitPrice * row.quantity)
      
      // 同步数量和单价
      if (row.calculation.quantity) {
        row.quantity = row.calculation.quantity
      }
      if (row.calculation.taxUnitPrice) {
        row.unitPrice = row.calculation.taxUnitPrice
      }
      
      calculateTotalAmount()
    }
    
    // 计算总金额
    const calculateTotalAmount = () => {
      const total = quotationForm.items.reduce((sum, item) => {
        return sum + (item.totalAmount || 0)
      }, 0)
      
      quotationForm.totalAmount = total
      quotationForm.totalTaxAmount = quotationForm.isTaxIncluded ? total : total * 1.13
    }
    
    // 计算成本合计 - 只计算界面上显示的7个字段
    const calculateTotalCost = (costs) => {
      if (!costs) return 0
      return (costs.basePrice || 0) + 
             (costs.flameRetardantFee || 0) + 
             (costs.copperPlatingFee || 0) + 
             (costs.surfaceTreatmentFee || 0) + 
             (costs.engineeringFee || 0) + 
             (costs.shippingFee || 0) + 
             (costs.copperThicknessFee || 0)
    }

    // 获取成本合计 - 实时计算界面显示的7个费用字段之和
    const getCostTotal = (costs) => {
      if (!costs) return 0
      
      // 确保所有字段都是数字类型
      const basePrice = Number(costs.basePrice) || 0
      const flameRetardantFee = Number(costs.flameRetardantFee) || 0
      const copperPlatingFee = Number(costs.copperPlatingFee) || 0
      const surfaceTreatmentFee = Number(costs.surfaceTreatmentFee) || 0
      const engineeringFee = Number(costs.engineeringFee) || 0
      const shippingFee = Number(costs.shippingFee) || 0
      const copperThicknessFee = Number(costs.copperThicknessFee) || 0
      
      return basePrice + flameRetardantFee + copperPlatingFee + 
             surfaceTreatmentFee + engineeringFee + shippingFee + 
             copperThicknessFee
    }
    
    // 处理客户代码选择变化
    const handleCustomerChange = (customerCode) => {
      const selectedCustomer = customers.value.find(c => c.customerCode === customerCode)
      if (selectedCustomer) {
        quotationForm.customerName = selectedCustomer.customerName
      }
    }

    // 处理客户名称选择变化
    const handleCustomerNameChange = (customerName) => {
      const selectedCustomer = customers.value.find(c => c.customerName === customerName)
      if (selectedCustomer) {
        quotationForm.customerCode = selectedCustomer.customerCode
      }
    }

    // 数据预处理：将customFields数组转换为JSON字符串，并确保数值字段为数字类型
    const preprocessQuotationData = (data) => {
      const processedData = { ...data }
      
      if (processedData.items && Array.isArray(processedData.items)) {
        processedData.items = processedData.items.map(item => {
          const processedItem = { ...item }
          
          // 将customFields数组转换为JSON字符串
          if (processedItem.customFields && Array.isArray(processedItem.customFields)) {
            processedItem.customFields = JSON.stringify(processedItem.customFields)
          }
          
          // 确保所有数值字段都是数字类型
          const numberFields = ['quantity', 'unitPrice', 'sampleFee', 'engineeringFee', 'urgentFee', 
                               'impedanceFee', 'testingFee', 'shippingFee', 'taxAmount', 'otherFee', 'totalAmount']
          
          numberFields.forEach(field => {
            if (processedItem[field] !== null && processedItem[field] !== undefined && processedItem[field] !== '') {
              const value = processedItem[field]
              if (field === 'unitPrice' && (value === '无' || value === 'N/A')) {
                // 保持"无"这样的特殊值
                processedItem[field] = value
              } else {
                processedItem[field] = Number(value) || 0
              }
            }
          })
          
          // 处理calculation对象
          if (processedItem.calculation) {
            const calcFields = ['widthMm', 'lengthMm', 'orderAreaMm', 'pricePerSqm', 'untaxUnitPrice', 
                               'untaxAmount', 'testingFee', 'untaxTotalAmount', 'taxTotalAmount', 'taxUnitPrice']
            
            calcFields.forEach(field => {
              if (processedItem.calculation[field] !== null && processedItem.calculation[field] !== undefined) {
                processedItem.calculation[field] = Number(processedItem.calculation[field]) || 0
              }
            })
          }
          
          // 处理costs对象
          if (processedItem.costs) {
            const costFields = ['basePrice', 'flameRetardantFee', 'copperPlatingFee', 'surfaceTreatmentFee',
                               'engineeringFee', 'shippingFee', 'copperThicknessFee', 'oversizeHoleFee',
                               'impedanceFee', 'halfHoleFee', 'mergePanelFee', 'resinPlugHoleFee',
                               'goldFingerFee', 'totalCost']
            
            costFields.forEach(field => {
              if (processedItem.costs[field] !== null && processedItem.costs[field] !== undefined) {
                processedItem.costs[field] = Number(processedItem.costs[field]) || 0
              }
            })
          }
          
          return processedItem
        })
      }
      
      // 确保顶级数值字段也是数字类型
      if (processedData.totalAmount !== null && processedData.totalAmount !== undefined) {
        processedData.totalAmount = Number(processedData.totalAmount) || 0
      }
      
      return processedData
    }
    
    // 保存草稿
    const saveDraft = async () => {
      try {
        saving.value = true
        quotationForm.status = '草稿'
        const processedData = preprocessQuotationData(quotationForm)
        const response = await quotationAPI.updateQuotation(quotationForm.id, processedData)
        if (response.code === 200) {
          ElMessage.success('草稿保存成功')
          emit('close', true)
        }
      } catch (error) {
        console.error('保存草稿失败:', error)
      } finally {
        saving.value = false
      }
    }
    
    // 保存报价单
    const saveQuotation = async () => {
      if (!quotationFormRef.value) return
      
      try {
        const valid = await quotationFormRef.value.validate()
        if (valid) {
          submitting.value = true
          const processedData = preprocessQuotationData(quotationForm)
          const response = await quotationAPI.updateQuotation(quotationForm.id, processedData)
          if (response.code === 200) {
            ElMessage.success('报价单保存成功')
            emit('close', true)
          }
        }
      } catch (error) {
        console.error('保存报价单失败:', error)
      } finally {
        submitting.value = false
      }
    }
    
    // 获取客户选项
    const fetchCustomers = async () => {
      try {
        const response = await customerAPI.getAllCustomers()
        if (response.code === 200) {
          customers.value = response.data
        }
      } catch (error) {
        console.error('获取客户列表失败:', error)
      }
    }
    
    // 获取业务员选项
    const fetchEmployees = async () => {
      try {
        const response = await employeeAPI.getAllEmployees()
        if (response.code === 200) {
          employees.value = response.data
        }
      } catch (error) {
        console.error('获取业务员列表失败:', error)
      }
    }
    
    // 加载报价单详情
    const loadQuotationDetail = async () => {
      try {
        loading.value = true
        const response = await quotationAPI.getQuotationById(props.quotationId)
        if (response.code === 200) {
          const data = response.data
          // 填充表单数据
          Object.keys(quotationForm).forEach(key => {
            if (data[key] !== undefined) {
              quotationForm[key] = data[key]
            }
          })
          
          // 初始化物料项的计算和成本对象
          quotationForm.items.forEach(item => {
            if (!item.calculation) {
              item.calculation = {
                widthMm: 0,
                lengthMm: 0,
                quantity: item.quantity || 0,
                orderAreaMm: 0,
                pricePerSqm: 0,
                untaxUnitPrice: 0,
                untaxAmount: 0,
                testingFee: 0,
                untaxTotalAmount: 0,
                taxTotalAmount: 0,
                taxUnitPrice: 0
              }
            }
            if (!item.costs) {
              item.costs = {
                basePrice: 0,
                flameRetardantFee: 0,
                copperPlatingFee: 0,
                surfaceTreatmentFee: 0,
                engineeringFee: 0,
                shippingFee: 0,
                copperThicknessFee: 0,
                oversizeHoleFee: 0,
                impedanceFee: 0,
                halfHoleFee: 0,
                mergePanelFee: 0,
                resinPlugHoleFee: 0,
                goldFingerFee: 0,
                totalCost: 0
              }
            }
          })
        }
      } catch (error) {
        console.error('加载报价单详情失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 监听含税状态变化
    watch(() => quotationForm.isTaxIncluded, () => {
      quotationForm.items.forEach(item => {
        calculateAmount(item)
      })
    })
    
    // 处理输入框变化
    const onInputChange = (value, obj, prop, allowDecimal = false) => {
      // 根据是否允许小数，过滤不合法字符
      let filteredValue = value;
      if (allowDecimal) {
        // 允许小数的正则表达式（允许数字和小数点）
        filteredValue = value.replace(/[^\d.]/g, '');
        // 确保只有一个小数点
        const parts = filteredValue.split('.');
        if (parts.length > 2) {
          filteredValue = parts[0] + '.' + parts.slice(1).join('');
        }
      } else {
        // 只允许整数的正则表达式
        filteredValue = value.replace(/\D/g, '');
      }
      
      // 更新模型值
      obj[prop] = filteredValue === '' ? 0 : (allowDecimal ? parseFloat(filteredValue) : parseInt(filteredValue));
      
      // 同步数量字段
      if (prop === 'quantity') {
        if (obj.calculation) {
          obj.calculation.quantity = obj.quantity;
        } else if (obj.quantity !== undefined) {
          const item = quotationForm.items.find(item => item.calculation === obj);
          if (item) {
            item.quantity = obj.quantity;
          }
        }
      }
      
      // 计算相关金额
      if (obj.calculation || ['quantity', 'unitPrice'].includes(prop)) {
        const row = obj.calculation ? quotationForm.items.find(item => item.calculation === obj) : obj;
        if (row) {
          calculateAmount(row);
        }
      }
    };
    
    // 组件挂载时的初始化
    onMounted(() => {
      fetchCustomers()
      fetchEmployees()
      loadQuotationDetail()
    })
    
    return {
      quotationFormRef,
      activeTab,
      loading,
      saving,
      submitting,
      quotationForm,
      customers,
      employees,
      rules,
      getStatusTagType,
      addItem,
      removeItem,
      calculateAmount,
      calculateTotalCost,
      getCostTotal,
      calculateTotalAmount,
      handleCustomerChange,
      handleCustomerNameChange,
      saveDraft,
      saveQuotation,
      onInputChange
    }
  }
}
</script>

<style>
.quotation-edit {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
}

.form-section :deep(.el-card__header) {
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.form-section :deep(.el-card__body) {
  padding: 20px;
}

/* 修复输入数字框样式 */
.full-width-input {
  width: 100%;
}

:deep(.el-table .el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #606266;
  opacity: 1;
  visibility: visible;
  height: 28px; /* 确保足够高度显示内容 */
  font-size: 14px; /* 设置合适的字体大小 */
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  width: 24px;
  height: 28px;
  line-height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
}

:deep(.el-table .el-select) {
  width: 100%;
}

:deep(.el-table .el-date-picker) {
  width: 100%;
}

/* 表格单元格内容样式优化 */
:deep(.el-table .cell) {
  padding-left: 8px;
  padding-right: 8px;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}

.footer-actions {
  text-align: center;
  padding: 20px 0 10px;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

.footer-actions .el-button {
  margin: 0 10px;
}

/* 数字输入框样式 */
.number-input {
  width: 100%;
  text-align: center;
}

:deep(.number-input .el-input__inner) {
  text-align: center;
}

/* 表格样式优化 */
:deep(.el-table .cell) {
  padding-left: 8px;
  padding-right: 8px;
}
</style> 